package Server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import client.Login;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.*;
import ocsf.server.AbstractServer;
import ocsf.server.ConnectionToClient;

public class login {
	
	

	/**
	 * @author Daniel
	 * @param con1 Connection to the database
	 * @param log Array of String which describs users quary paramaters
	 * @return Array of String which describs users information if it was a successful login or a code if it was unseccessful
	 */
	public static String[] chackvalidation(Connection con1,String[] log )
	{
		String[] result = new String[6];
		/*
		result[2]=null;
		result[3]=null;
		result[4]=null;
		*/
		 try
         {
             Statement stmt = con1.createStatement();
            java.sql.PreparedStatement ps = con1.prepareStatement("SELECT * FROM users WHERE username= ? and password= ?;");
             ps.setObject(1, log[1]);
             ps.setObject(2, log[2]);
          // state:1=incorrect pass ; 2=user does not exist ; 3=user already
     		// logged ; 4=success
             ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE username='" + log[1] + "'");
             
             if (res.next()) {
            	
  				  				
     			if (!(res.getString(3).equals(log[2])))
     				result[1]="1";
     			else
     			if (res.getBoolean(4) == true)
     				result[1]="3";
     			else
     			{
     				result[0]="logoff";    
     				result[1]="4";     				     			
     				result[2]=res.getString(5);
      				result[3]=res.getString(2);
      				result[4]=res.getString(3);
      				result[5]=res.getString(6);
      				
     				stmt.executeUpdate("UPDATE users SET logged=1 WHERE username='"
     						+ log[1] + "'");     				
	
     			}

     		} else     		
     			result[1]="2";

     		res.close();
     	} catch (SQLException e) {
     		e.printStackTrace();
     	}
		
		
		return result;
		
	}

}
